<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\model\Task as TaskModel;
use app\common\model\user\Activity as UserActivityModel;
use app\common\model\user\Company;
use app\common\model\user\Favorite;
use app\common\model\user\Feedback;
use app\common\model\user\Friend;
use app\common\model\user\Order;
use fast\Random;
use think\Config;
use think\Validate;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third',
        'schoolUser',
        'wxlogin',
        'companyList',
        'company',
        'wxCallback',
    ];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }

    /**
     * 会员中心
     */
    public function index()
    {
        $this->success('', ['welcome' => $this->auth->nickname]);
    }

    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @param string $account 账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    public function info()
    {
        $userId = $this->auth->id;
        $user = \app\common\model\User::get($userId, ['company']);
        $user->hidden([
            'password',
            'salt',
            'mobile',
            'money',
        ]);

        $this->success('', $user);
    }

    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @param string $mobile 手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email 邮箱
     * @param string $mobile 手机号
     * @param string $code 验证码
     */
    public function register()
    {
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $email = $this->request->post('email');
        $mobile = $this->request->post('mobile');
        $code = $this->request->post('code');
        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }
        $ret = $this->auth->register($username, $password, $email, $mobile, []);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar 头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio 个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        $data = $this->request->post();
        if (!$avatar) {
            unset($data['avatar']);
        }
        $user->save($data);
        $this->success('操作成功');
//        $this->success('信息已提交，审核中');
    }

    /**
     * 修改邮箱
     *
     * @ApiMethod (POST)
     * @param string $email 邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->post('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @param string $mobile 手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 第三方登录
     *
     * @ApiMethod (POST)
     * @param string $platform 平台名称
     * @param string $code Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->post("platform");
        $code = $this->request->post("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo' => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @param string $mobile 手机号
     * @param string $newpassword 新密码
     * @param string $captcha 验证码
     */
    public function resetpwd()
    {
        $type = $this->request->post("type", "mobile");
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    public function wxlogin()
    {
        $openid = $this->request->post('openid');
        $mobile = $this->request->post('mobile');
        if (!$openid) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->wxlogin($openid, $mobile);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    public function schoolUser()
    {
        $nickname = $this->request->get('nickname');

        $userId = (int)$this->auth->id;
        if (!$userId) {
//            $this->success('', []);
        }
        $userModel = new \app\common\model\User();
        $user = $userId ? $userModel->find($userId) : null;
        $list = $userModel
            ->with(['company'])
            ->field(['id', 'nickname', 'avatar', 'gender', 'mobile', 'school_id', 'school_education', 'company_name', 'company_position', 'company_industries'])
            ->where('id', '<>', $userId)
            ->where(function ($query) use ($user, $nickname) {
                if ($user) {
//                    if ($user->school_id) {
//                        $query->where('school_id', $user->school_id);
//                    } else {
//                        $query->whereRaw('1 != 1');
//                    }
                }
                if ($nickname) {
                    $query->whereLike('nickname', "%{$nickname}%");
                }
            })->order('id', 'desc')->select();
        foreach ($list as $v) {
            $v->is_school = ($user && $user->school_id == $v->school_id) ? 1 : 0;
        }
        $this->success('', $list);
    }

    public function friendUser()
    {
        $userId = (int)$this->auth->id;
        $friendModel = new Friend();
        $list = $friendModel->where('status', Friend::STATUS_TG)
            ->where(function ($query) use ($userId) {
                $query->where('from_user_id', $userId)->whereOr('to_user_id', $userId);
            })
            ->select();
        $userIds = array_unique(array_merge($list->column('from_user_id'), $list->column('to_user_id')));
        if (!$userIds) {
            $this->success('', []);
        }
        $userModel = new \app\common\model\User();
        $list = $userModel
            ->field(['id', 'nickname', 'avatar', 'gender', 'school_id', 'company_name', 'company_position', 'company_industries'])
            ->where('id', '<>', $userId)
            ->whereIn('id', $userIds)->select();

        $this->success('', $list);
    }

    public function userInfo()
    {
        $userId = $this->auth->id;
        $id = $this->request->get('id');
        if (!$id) {
            $this->error(__('Invalid parameters'));
        }
        $user = \app\common\model\User::get($id, ['task', 'company']);
        $user->hidden(['username', 'password', 'salt', 'token', 'email', 'money']);
        $user->friend = 0;
        $friend = Friend::where('status', Friend::STATUS_TG)
            ->where(function ($query) use ($userId, $id) {
                $query->where(['from_user_id' => $id, 'to_user_id' => $userId])
                    ->whereOr(['from_user_id' => $userId, 'to_user_id' => $id]);
            })
            ->count();
        if ($friend) {
            $user->friend = 1;
        }
        $this->success('', $user);
    }

    public function addFriend()
    {
        $id = $this->request->post('id');
        $userId = $this->auth->id;
        if (!$id) {
            $this->error(__('Invalid parameters'));
        }
        $user = \app\common\model\User::get($id);
        if (!$user) {
            $this->error('用户不存在');
        }
        $friend = Friend::where(function ($query) use ($userId, $id) {
            $query->where(['from_user_id' => $id, 'to_user_id' => $userId])
                ->whereOr(['from_user_id' => $userId, 'to_user_id' => $id]);
        })->count();
        if ($friend) {
            $this->error(__('您已添加过该用户'));
        }
        Friend::create([
            'from_user_id' => $userId,
            'to_user_id' => $id,
            'status' => Friend::STATUS_WT,
        ]);
        $this->success();
    }

    public function delFriend()
    {
        $id = $this->request->post('id');
        $userId = $this->auth->id;
        if (!$id) {
            $this->error(__('Invalid parameters'));
        }
        $user = \app\common\model\User::get($id);
        if (!$user) {
            $this->error('用户不存在');
        }
        Friend::where(function ($query) use ($userId, $id) {
            $query->where(['from_user_id' => $id, 'to_user_id' => $userId])
                ->whereOr(['from_user_id' => $userId, 'to_user_id' => $id]);
        })->delete();
        $this->success();
    }

    public function company()
    {
        $id = $this->request->get('id');
        $userId = $this->auth->id;
        $company = Company::where(function ($query) use ($id, $userId) {
            if ($id) {
                $query->where('id', $id);
            } else {
                $query->where('user_id', $userId);
            }
        })->find();
        $user = \app\common\model\User::get($company ? $company->user_id : 0);
        $company->is_school = 0;
        if ($user && $user->school_id == 8) {
            $company->is_school = 1;
        }
        $this->success('', $company);
    }

    public function companyList()
    {
        $list = Company::all();
        $this->success('', $list);
    }

    public function saveCompany()
    {
        $data = $this->request->post();

        $company = Company::where('user_id', $this->auth->id)->find();
        if ($company) {
            $company->save($data);
        } else {
            $data['user_id'] = $this->auth->id;
            $company = Company::create($data);
        }
        $this->success('', $company);
    }

    public function star()
    {
        $mapIds = Favorite::where('user_id', $this->auth->id)->column('map_id');
        $list = $mapIds ? \app\common\model\Course::whereIn('id', $mapIds)->select() : [];
        foreach ($list as &$value) {
            $value->user_star = 1;
        }
        unset($value);
        $this->success('', $list);
    }

    public function activity()
    {
        $list = UserActivityModel::with(['activity'])
            ->where('user_id', $this->auth->id)
            ->where('status', UserActivityModel::STATUS_SUCC)
            ->select();

        $this->success('', $list);
    }

    public function saveActivity()
    {
        $id = $this->request->post('id');
        $name = $this->request->post('name');
        $mobile = $this->request->post('mobile');
        if (!$id || !$name || !$mobile) {
            $this->error(__('Invalid parameters'));
        }

        $activity = \app\common\model\Activity::withCount(['userCount'])->find($id);
        if (!$activity) {
            $this->error('活动不存在');
        }
        if ($activity->status == 0) {
            $this->error('活动已停止报名');
        }
        if ($activity->number <= $activity->user_count_count) {
            $this->error('名额已满');
        }

        $data = UserActivityModel::create([
            'activity_id' => $id,
            'name' => $name,
            'mobile' => $mobile,
            'user_id' => $this->auth->id,
            'money' => $activity->price,
        ]);

        $this->success('', $data);
    }

    public function feedback()
    {
        $data = $this->request->post();
        if (empty($data['content'])) {
            $this->error(__('Invalid parameters'));
        }
        $data['user_id'] = $this->auth->id;
        Feedback::create($data);

        $this->success();
    }

    public function addOrder()
    {
        $user_id = $this->auth->id;
        $course_id = $this->request->post('course_id');
        $course = \app\common\model\Course::find($course_id);
        if (!$course) {
            $this->error('课程不存在');
        }
        $order = Order::where(['user_id' => $user_id, 'course_id' => $course_id])->find();
        if ($order) {
            if ($order->status == 0) {
                $order->money = $course->price;
                $order->save();
                $this->success('', $order);
            }
            $this->error('您已购买过该课程');
        }

        $order = Order::create([
            'user_id' => $user_id,
            'course_id' => $course_id,
            'money' => $course->price,
            'status' => Order::STATUS_NON_PAY,
        ]);
        $this->success('', $order);
    }

    public function wxCallback()
    {
        $type = $this->request->post('type', '');
        $orderId = $this->request->post('attach', '');
        $transactionId = $this->request->post('transactionId', '');
        if (!$orderId || !$transactionId) {
            $this->error(__('Invalid parameters'));
        }

        if ($type == 1) {
            $order = Order::get(['id' => $orderId]);
            if (!$order) {
                $this->error(__('Invalid parameters'));
            }
            if ($order->status == Order::STATUS_SUCC) {
                $this->success();
            }
            $order->status = Order::STATUS_SUCC;
            $order->transaction_id = $transactionId;
            $order->paytime = date('Y-m-d H:i:s');
            $order->save();
        } else if ($type == 2) {
            $activity = \app\common\model\user\Activity::where('id', $orderId)->find();
            if (!$activity) {
                $this->error(__('Invalid parameters'));
            }
            if ($activity->status == Order::STATUS_SUCC) {
                $this->success();
            }
            $activity->status = Order::STATUS_SUCC;
            $activity->transaction_id = $transactionId;
            $activity->paytime = date('Y-m-d H:i:s');
            $activity->save();
        }

        $this->success();
    }

    public function orderList()
    {
        $userId = $this->auth->id;
        $list = Order::with(['course'])
            ->where('user_id', $userId)
            ->where('status', Order::STATUS_SUCC)
//            ->field(['course_id', 'money', 'status', 'paytime', 'createtime'])
            ->select();
        $this->success('', $list);
    }

    public function auditCount()
    {
        $userId = $this->auth->id;
        $count = TaskModel::where('user_id', $userId)
            ->group('audit_status')
            ->fieldRaw('audit_status, count(*) as count')
            ->select();
        $count = $count->column('count', 'audit_status');
        $this->success('', [
            ['audit_status' => TaskModel::AUDIT_STATUS_WAIT, 'count' => $count[TaskModel::AUDIT_STATUS_WAIT] ?? 0],
            ['audit_status' => TaskModel::AUDIT_STATUS_PASS, 'count' => $count[TaskModel::AUDIT_STATUS_PASS] ?? 0],
            ['audit_status' => TaskModel::AUDIT_STATUS_REFUSE, 'count' => $count[TaskModel::AUDIT_STATUS_REFUSE] ?? 0],
        ]);
    }

    public function taskList()
    {
        $user_id = $this->auth->id;
        $audit_status = $this->request->get('audit_status');

        $model = new TaskModel();
        $list = $model->with(['user.companyName'])
            ->where(function ($query) use ($user_id, $audit_status) {
                if ($user_id) {
                    $query->where('user_id', $user_id);
                }
                if (!is_null($audit_status)) {
                    $query->where('audit_status', $audit_status);
                }
            })->order('updatetime', 'desc')->select();
        $this->success('', $list);
    }
}
